//import isArray from 'lodash/isArray'
//import trim from 'lodash/trim'
//import cloneDeep from 'lodash/cloneDeep'
import { wmsPost } from '@/project/pda/api/api'
import { getStorage, getUrlSystemApp } from '@/utils/tools'
import { replaseRegVariable, processingConstant } from '@ve/utils/utils'
import isPlainObject from 'lodash/isPlainObject'

export default function printByBlueTooth({ vm, action, done, callbackData }) {
  console.log('蓝牙打印-----------vm', vm)
  console.log('蓝牙打印-----------callbackData', callbackData)
  console.log('蓝牙打印-----------action', action)

  let config = action.extension

  //选中的模板ID
  let REPORT_CODE = config.getPrintModule.value
  let method = config.requestConfig.value.method
  let PRINT_CODE_ARR = []

  //定义一个空对象
  let _data = {}
  _data['ORG_ID'] = getStorage(`orgCode_${getUrlSystemApp()}`)
  _data['WAREHOUSE_ID'] = getStorage(`wareHoseId_${getUrlSystemApp()}`)
  _data['REPORT_CODE'] = REPORT_CODE

  //遍历配置的请求参数
  config.requestConfig.value.data.forEach((v) => {
    console.log('isPlainObject', isPlainObject(v.value), v)
    if (isPlainObject(v.value)) {
      let _value = ''
      const moduleId = v.value.sourceId.value.source[0] || ''
      // 如果参数值是对象的话 则代表是复杂参数 则需要找到对应模块取值
      if (!moduleId) return
      const formItem = vm.vuiComponents[moduleId] //获取选中得组件
      console.log('formItem===', formItem)
      const _formModule = formItem.self.formId && vm.vuiComponents[formItem.self.formId].self
      const _formModel = formItem.self.info.extension.model && formItem.self.info.extension.model.value
      if (_formModule && _formModel) {
        _value = _formModule.info.data.formData[_formModel]
        // console.log('pda调用接口2', _value)
      } else {
        _value = formItem.self.formDataModel
      }
      //
      // 通过这个 moduleId ，在vm.vuiComponents里面拿到组件实例（self）
      _data[v.key] = processingConstant(vm, _value)
    } else {
      // 给输入框设置死得值
      _data[v.key] = processingConstant(vm, v.value)
      // }
    }
    // requestObj[item.key] = item.value
  })

  //请求打印接口,返回蓝牙指令
  wmsPost(_data, method)
    .then((res) => {
      console.log('res', res)
      //遍历接口结果集
      res.data.print_data.forEach((item) => {
        PRINT_CODE_ARR.push(replaseRegVariable(res.data.print_code, item))
      })
      console.log(PRINT_CODE_ARR.join(''))
      //请求打印接口获取蓝牙指令
    })
    .catch((err) => {
      console.log('err', err)
    })

  setTimeout(() => {
    window.$CIMC.connectBlueToothPrint('CALLBACK', PRINT_CODE_ARR.join(''))
  }, 500)

  done(null, {})
}
